<?php class Popup extends Front_Controller {
 	function __construct()
	{
		parent::__construct();
		$this->load->model("popup_model","popup");
	}
	function register(){
		$this->form_validation->set_rules('email','email','callback_check_email');
		if ($this->form_validation->run() == TRUE){
			$this->load->helper("option");
			$post = $this->input->post();		
			$category_product_id = save_options($post["category_product_id"]);
			$password = generateRandomString(6);
			$password_insert = sha1($password);
			$array_email = explode("@",$post["email"]);
			$fullname 	 = $array_email[0];
			
			$insert_data = array("fullname"=>$fullname,"email"=>$post["email"],"phone"=>$post["phone"],"group_id"=>1,"active"=>1,"email_subscribe"=>1,"country_zone_id"=>$post["country_zone_id"],"category_product_id"=>$category_product_id,"password"=>$password_insert,"score"=>$this->config->item("score_register"),"created"=>time(),"code_active"=>md5($post["email"]));
			
			$this->popup->insert("customers",$insert_data);
			
			$this->sendmail($insert_data,$password);
			$data["err"] = 0;
			$data["mes"] = $this->load->view("popup/mess_success","",true);
			$time = time() + 60*60;
		}else{
			$data["err"] = 1;
			$data["mes"] = validation_errors();
		}
		echo json_encode($data);exit;
	}
	function sendmail($inser_data,$password){
		$inser_data["password"] = $password;
		$messenger = $this->load->view("popup/content_email",$inser_data,true);
		$subject   = "Bạn đã đăng ký thành viên thành công trên Plus Mainichi.";
		$email_to  = $inser_data["email"]; 
		$this->load->helper("email");
		send_mail($subject,$email_to,$messenger);
	}
	function check_email(){
		$email = $this->input->post("email");
		 if(empty($email)){
			$this->form_validation->set_message('check_email', 'Vui lòng nhập %s');
		 	return false;
		 }
		$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
		if(!eregi($pattern,$email)){
			$this->form_validation->set_message('check_email', '%s không đúng định dạng');
		 	return false;
		}
		$check_email = $this->db->get_where("customers",array("email"=>$email))->row();
		if (!empty($check_email)){
			$this->form_validation->set_message('check_email', '%s đã tồn tại');
			return false;
		}
		return true;
	}
	
}?>